/*
 * Copyright (C) 2025 Tsingteng MicroSystem
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "nfc_osi_api.h"
#include "nfc_types.h"
#include <time.h>
#include <unistd.h>

/**
 * @brief OSI时间相关接口
 * @file osi_time.c
*/

/**
 * @brief 获取当前系统时间戳，单位毫秒
 *
 * @param ms 返回时间戳
 *
 * @return 获取成功时返回NFC_STATUS_OK，失败时返回对应错误码
*/
tNFC_STATUS osi_curr_time_ms(tTIMESTAMP *ms)
{
    if (ms == NULL) {
        return NFC_STATUS_INVALID_PARAM;
    }
    struct timespec ts;
    int ret = clock_gettime(CLOCK_REALTIME, &ts);
    if (ret != 0) {
        return NFC_STATUS_FAILED;
    }
    *ms = ts.tv_sec * OSI_MS_PER_SEC + (ts.tv_nsec / OSI_NS_PER_MS);
    return NFC_STATUS_OK;
}

/**
 * @brief 获取系统启动时间戳，单位毫秒
 *
 * @param ms 返回时间戳
 *
 * @return 获取成功时返回NFC_STATUS_OK，失败时返回对应错误码
*/
tNFC_STATUS osi_boot_time_ms(tTIMESTAMP *ms)
{
    if (ms == NULL) {
        return NFC_STATUS_INVALID_PARAM;
    }
    struct timespec ts;
    int ret = clock_gettime(CLOCK_MONOTONIC, &ts);
    if (ret != 0) {
        return NFC_STATUS_FAILED;
    }
    *ms = ts.tv_sec * OSI_MS_PER_SEC + (ts.tv_nsec / OSI_NS_PER_MS);
    return NFC_STATUS_OK;
}

/**
 * @brief 睡眠指定时间
 *
 * @param us 睡眠时间，单位为微秒
*/
void osi_usleep(uint64_t us)
{
    usleep(us);
}
